<template>
    <div>
        <div class="mt-10">
            <div class="title mt6">{{ 'SMTP ' + $t('邮箱服务器配置') }}</div>
            <div style="width: 600px;" class="mt-22 ml-22">
                <a-form :form="formstmp" @submit="smtpSubmit" labelAlign="left">
                    <a-spin :spinning="loading">
                        <div class="bg">
                            <a-form-item :label="'SMTP' + $t('Set')" v-bind='formlayout'>
                                <a-input v-decorator="['host', {
                                    initialValue: stmpdata.host, rules: [{
                                        required: true, message: $t('Enter') + $t('Set'),
                                        pattern: /^[A-Za-z0-9.]+$/, message: $t('Only_num_letter_dots')
                                    }]
                                }]" :placeholder="$t('example') + 'smtp.wuzhoucloud.com'">
                                </a-input>
                            </a-form-item>
                            <a-form-item label='SMTP SSL' v-bind='formlayout'>
                                <a-radio-group @change="radioChange" v-decorator="['ssl', {
                                    rules: [{ required: true, message: $t('Choose') }],
                                    initialValue: stmpdata.ssl
                                }]">
                                    <a-radio :value="true">{{ $t('Yes') }}</a-radio>
                                    <a-radio :value="false">{{ $t('No') }}</a-radio>
                                </a-radio-group>
                            </a-form-item>
                            <a-form-item :label="'SMTP ' + $t('Port')" v-bind='formlayout'>
                                <a-input v-decorator="['port', {
                                    initialValue: stmpdata.port, rules: [{
                                        required: true, message: $t('Enter') + $t('Port'),
                                        pattern: /^[0-9]*$/, message: $t('Only_num')
                                    }]
                                }]">
                                </a-input>
                            </a-form-item>
                            <a-form-item :label="'SMTP ' + $t('Account')" v-bind='formlayout'>
                                <a-input v-decorator="['emuser', {
                                    initialValue: stmpdata.emuser, rules: [{
                                        required: true, message: $t('Enter') + $t('Account'),
                                        pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: $t('Enter_valid_email')
                                    }]
                                }]">
                                </a-input>
                            </a-form-item>
                            <a-form-item :label="'SMTP ' + $t('Password')" v-bind='formlayout'>
                                <a-input-password v-decorator="['password', {
                                    initialValue: stmpdata.password, rules: [{
                                        required: true, message: $t('Enter') + $t('Password'),
                                        pattern: /^[^\s]{1,128}$/, message: $t('不能为空且长度控制在1-128 字符')
                                        // pattern: /^[a-zA-Z]\w{5,17}$/, message: $t('SMTP_rule_prompt')
                                    }]
                                }]">
                                </a-input-password>
                            </a-form-item>
                        </div>
                    </a-spin>
                    <div class="btn" v-userAuth="'F4-2'">
                        <a-button type="primary" html-type="submit">{{ $t('Save') }}</a-button>
                        <a-button @click="resetstmp"
                            style="color: #666666; border: solid 1px #999999; margin-left: 1em;">{{ $t('Reset')
                            }}</a-button>
                    </div>
                </a-form>
                <!-- <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol"
                    :wrapper-col="wrapperCol" labelAlign="left">
                    <a-spin :spinning="loading">
                        <a-form-model-item :label="$t('SMTP ') + $t('设置') + ':'" prop="set">
                            <a-input v-model="form.set" :placeholder="$t('Enter') + $t('名称')" />
                        </a-form-model-item>
                        <a-form-model-item :label="$t('SMTP ') + $t('SSL') + ':'" prop="ssl">
                            <a-radio-group v-model:value="form.ssl">
                                <a-radio value="true">是</a-radio>
                                <a-radio value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-model-item>
                        <a-form-model-item :label="$t('SMTP ') + $t('端口') + ':'" prop="port">
                            <a-input v-model="form.port" :placeholder="$t('Enter') + $t('名称')" />

                        </a-form-model-item>
                        <a-form-model-item :label="$t('SMTP ') + $t('账户') + ':'" prop="account">
                            <a-input v-model="form.account" :placeholder="$t('Enter') + $t('名称')" />
                        </a-form-model-item>
                        <a-form-model-item :label="$t('SMTP ') + $t('密码') + ':'" prop="pwd">
                            <a-input v-model="form.pwd" :placeholder="$t('Enter') + $t('名称')" type="password" />
                        </a-form-model-item>
                    </a-spin>
                    <a-form-model-item>
                        <a-button type='primary' @click="handleSave">{{ $t('Save') }}</a-button>
                        <a-button class="ml-24" @click="handleCancel">{{ $t('重置') }}</a-button>
                    </a-form-model-item>
                </a-form-model> -->
            </div>

            <a-divider />

            <div class="title mt-24">{{ $t('接收邮箱配置') }}</div>
            <div class="tips border-primary j-border-radius-sm pt-10 pb-10 pl-10 pr-20 mt-12 tipstyle">
                <!-- <i class="icon icon-tips16f j-text-main"></i> -->
                <Iconfont class="icon pt-4 pr-4" type="a-16_f_ic_about" style="color: #2d74ff;"></Iconfont>
                {{ $t('进行有效性测试时，将会向添加的邮箱发送一条测试邮件。') }}
            </div>

            <div style="width: 600px;" class="mt-22 ml-22">
                <!-- <div style="display: flex;justify-content: space-between;align-items: center;">
                                <div style="color: #333333;">{{ $t('Receiving-mailbox') }}</div>
                                <a-switch v-userAuth="'F4-2'"  size="small" v-model="checkedEmail" @change="onChange('smtp', checkedEmail)" />
                            </div> -->

                <a-form labelAlign="left">
                    <a-form-item :label="$t('开启邮箱服务')" v-bind='formlayout' :required="true">
                        <a-switch v-model="checkedEmail" @change="onChange('smtp', checkedEmail)" />
                    </a-form-item>
                </a-form>
                <span>{{ $t('接收邮箱列表：') }}</span>
                <a-table class="mt-16" rowKey="id" :columns='columns' :loading="tableloading" :dataSource='emaildata'
                    :locale="defaultSetting" size='small' :pagination="false">

                    <template slot="address" slot-scope=" text, record ">
                        <span>{{ text }}</span>
                    </template>

                    <template slot="operate" slot-scope='text, record'>
                        <div style="display: flex;" v-userAuth="'H1-2'">
                            <span @click="del(record)" class="j-text-red cursor-pointer"> {{ $t('Delete') }}</span>
                        </div>
                    </template>
                </a-table>

                <div class="mt-20 mb-20">
                    <a @click="handleAdd">{{ $t('+ 新增') + $t('邮箱地址') }}</a>
                </div>

                <a-modal :title="$t('新增邮箱地址')" v-model='isAdd' :maskClosable='false' v-dragModal @cancel="handleClose">
                    <a-form :form="formmail" labelAlign="left" class="mt-16">
                        <a-row>
                            <!-- <a-col :span="20">
                            <a-form-item :label="$t('开启接收邮箱')" v-bind='formlayout'>
                                <a-switch v-model="checkedEmail" @change="onChange('smtp', checkedEmail)" />
                            </a-form-item>
                        </a-col> -->
                            <a-col :span="20">
                                <a-form-item :label="$t('Email')" v-bind='formlayout1' has-feedback>
                                    <a-auto-complete v-decorator="['mail', {
                                        rules: [{ required: true, message: $t('Enter') + 'Email' }, { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: $t('Enter_valid_email') }]
                                    }]" :dataSource="edata" @change="handleChange" :placeholder="$t('Enter') + 'Email'"
                                        allow-clear />
                                </a-form-item>
                            </a-col>
                            <!-- <a-col :span="4" v-userAuth="'F4-2'">
                            <a-form-item>
                                <a-button style="margin-left: 16px;" type="primary" @click="add">{{ $t('Add')
                                    }}</a-button>
                            </a-form-item>
                        </a-col> -->
                        </a-row>

                        <!-- <a-row style="border:1px solid #e8e8e8;height: 15.74em;overflow-y: auto;padding:1em">
                        <a-col v-for="(item, index) in emaildata" :key="index">
                            <p class="label"
                                style="padding:0 0.3em;display: flex;justify-content:space-between;align-items:center;">
                                <span class="addr" :title="item.addr">{{ item.addr }}</span>
                                <a-popconfirm :title="$t('Sure_confirm')" @confirm="del(item)" @cancel="cancel"
                                    :okText="$t('Yes')" :cancelText="$t('No')">
                                    <a-icon type="close-circle" twoToneColor="#cf1b47" />
                                </a-popconfirm>
                            </p>
                        </a-col>
                    </a-row> -->
                        <!-- <a-form-model-item class="mt-20">
                            <a-button style="color: #006db8;;margin-right: 1em;border: solid 1px #006db8;"
                                @click="emailConfigEffect">
                                {{ $t('Test-effect') }}
                            </a-button>
                            <a-button type='primary' :disabled="saveMail" @click="handleEmailSave">{{ $t('Save')
                                }}</a-button>
                        </a-form-model-item> -->
                    </a-form>
                    <template slot="footer">
                        <a-button type='primary' @click="emailConfigEffect" :loading="testloading">{{ $t('有效性测试') }}</a-button>
                        <a-button :disabled="saveMail" type='primary' @click="handleEmailSave">{{
                            $t('Save') }}</a-button>
                    </template>
                </a-modal>
            </div>

        </div>

    </div>
</template>

<script>
import request from '@/request/request'
import NoAuthPage from '@/components/common/NoAuthPage'
import { data } from 'jquery';
import EmptyData from '@/components/common/EmptyData'



export default {
    name: '',
    props: {
        mail: {
            type: Boolean,
            required: true
        }
    },
    components: { NoAuthPage },
    data() {
        return {
            formlayout: {
                labelCol: { span: 5 },
                wrapperCol: { span: 17 }
            },
            formlayout1: {
                labelCol: { span: 6 },
                wrapperCol: { span: 15 }
            },
            edata: [],
            emaildata: [],
            checkedEmail: false,
            // loading: false,
            // labelCol: { span: 6 },
            // wrapperCol: { span: 18 },
            emailList: [],
            formmail: this.$form.createForm(this),
            // form: {
            //     set: '1',
            //     ssl: 'true',
            //     port: '1',
            //     account: '',
            //     pwd: '',
            // },
            formstmp: this.$form.createForm(this),
            stmpdata: {
                ssl: true,
            },
            saveMail: true,

            defaultSetting: { emptyText: <EmptyData /> },
            isAdd: false,
            columns: [
                { title: this.$t('邮箱地址'), dataIndex: 'addr', key: 'addr', width: 180, scopedSlots: { customRender: "addr" } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 150, fixed: 'right' }
            ],
            tableloading: false,
            loading: false,
            testloading: false,

        }
    },

    mounted() {
        this.getemail()
        this.getFrequency()
        this.getstmp()
        this.checkedEmail = this.mail

    },

    methods: {
        getemail() {
            request('get', '/Alert/mail').then(res => {
                console.log('获取邮箱', res)
                if (res.data.flag == 1) {
                    this.model(res.data.id) //返回模板
                    this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                } else {
                    this.emaildata = res.data
                }
            })
        },
        handleSave() {
            this.$refs.ruleForm.validate(async valid => {
                if (valid) {
                    console.log("formdata", this.form)
                    // this.loading = true
                    // const { data } = await this.$api.data.appendGatewayOptionApi(this.form)
                    // this.model(data.id) //返回模板
                    // this.notice(data.id, data.params, data.flag) //通知列表显示
                    // if (data.flag == '0') {
                    //     this.$emit('get-list')
                    //     this.handleClose()
                    // }
                    // this.loading = false
                } else {
                    return false;
                }
            });
        },
        handleCancel() {
            this.$refs['ruleForm'].resetFields();
        },
        //获取SMTP邮箱服务配置
        getstmp() {
            // if (alldata && Object.keys(alldata).length !== 0) {
            //     // } else if (res.data != null) {
            //         // console.log("stmp", res.data)
            //         this.stmpdata = alldata
            //     } else {
            //         this.stmpdata.ssl = true
            //         // console.log("获取失败")
            //     }
            
            this.loading = true
            // request('get', 'ops/conf/db/stmp').then(res => {
            request('get', '/Alert/stmp').then(res => {
                if (res.data.flag == 1) {
                    this.model(res.data.id) //返回模板
                    this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                } else if (res.data && Object.keys(res.data).length !== 0) {
                // } else if (res.data != null) {
                    // console.log("stmp", res.data)
                    this.stmpdata = res.data
                } else {
                    this.stmpdata.ssl = true
                    // this.stmpdata = [{ ssl: true }]
                    // console.log("获取失败")
                }
                this.loading = false
            })
        },
        //修改SMTP邮箱服务器配置
        smtpSubmit(e) {
            e.preventDefault();
            this.formstmp.validateFields((err, values) => {
                if (!err) {
                    this.loading = true
                    request('put', '/Alert/stmp', values).then(res => {
                        // this.getstmp()
                        this.model(res.data.id) //返回模板
                        this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                        this.getstmp()
                        this.loading = false
                        // this.gettask()  //任务栏信息
                    })
                }
            });
        },

        //重置SMTP邮箱
        resetstmp() {
            this.formstmp.resetFields();
            this.stmpdata = [{ ssl: true }];
            this.formstmp.setFieldsValue({
                ssl: this.stmpdata[0].ssl
            });
            // 设置表单默认值
            // this.formstmp.setFieldsValue({
            //     ssl: true,  // 设置 field1 默认值
            // });
        },

        radioChange(e) {
        },

        handleChange(value) {
            // if(value){
            //     this.saveMail = true
            // }
            console.log("change", value)
            this.edata = !value || value.indexOf('@') >= 0 ? [] : [
                `${value}@gmail.com`,
                `${value}@163.com`,
                `${value}@qq.com`,
            ];
        },
        //测试邮箱配置有效性
        emailConfigEffect() {
            this.formmail.validateFields((err, values) => {
                if (!err) {
                    this.testloading = true
                    request('post', '/Alert/mail/checkout', {
                        mail: values.mail
                    }).then(res => {
                        this.model(res.data.id) //返回模板
                        this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                        if (res.data.flag == 0) {
                            this.saveMail = false
                        }
                        this.testloading = false
                    }).catch(err => {
                        console.log(err);
                    })
                }

            })

        },
        handleEmailSave(e) {
            e.preventDefault();
            this.formmail.validateFields((err, values) => {
                if (!err) {
                    request('put', '/Alert/mail', values).then(res => {
                        this.getemail()
                        this.model(res.data.id) //返回模板
                        this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                        // this.gettask()  //任务栏信息
                        this.formmail.resetFields();
                        // this.getemail()
                        // if(res.data.flag == 0) {
                        this.saveMail = true
                        this.isAdd = false
                        // }
                    })
                }
            });
        },
        add(e) {
            // e.preventDefault();
            // this.formmail.validateFields((err, values) => {
            //     if (!err) {
            //         request('post', '/Alert/mail', values).then(res => {
            //             this.getemail()
            //             this.model(res.data.id) //返回模板
            //             this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
            //             // this.gettask()  //任务栏信息
            //             this.formmail.resetFields();
            //             this.getemail()
            //         })
            //     }
            // });
        },

        //
        handleAdd() {
            this.isAdd = true
        },
        handleClose() {
            this.formmail.resetFields();
            this.isAdd = false
            this.saveMail = true
        },
        // 邮箱的删除
        del(item) {
            request('DELETE', '/Alert/mail', {
                // data:{
                id: item.id,
                url: item.addr
                // }
            }).then(res => {
                this.getemail()
                this.model(res.data.id) //返回模板
                this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                // this.gettask()  //任务栏信息
            })
        },
        cancel(e) {
        },
        async onChange(name, checked) {
            this.$emit('change-list', name, checked)
            // let flag = checked === true ? 1 : 0
            // const params = {
            //     [name]: flag
            // }
            // const item = {
            //     'hook': Number(this.checkedHook),
            //     'wechat': Number(this.checkedWechat),
            //     'snmp': Number(this.checkedSNMP),
            //     'smtp': Number(this.checkedEmail)
            // }
            // const { data } = await this.$api.alarm.modifyAlarmSwitch({ ...item, ...params });
            // if (data.flag == 1) {
            //     this.model(data.id) //返回模板
            //     this.notice(data.id, data.params, data.flag) //通知列表显示
            // } else {
            //     this.getFrequency()
            //     this.$message.success('修改成功！')
            // }
        },
        async getFrequency() {
            // await this.getSnmp()
            const { data: { mes } } = await this.$api.alarm.getAlarmSwitch();
            this.checkedEmail = !!mes.smtp
            this.checkedHook = !!mes.hook
            this.checkedWechat = !!mes.wechat
            this.checkedSNMP = !!mes.snmp
            // const { data } = await this.$api.alarm.getAlarmRate();
            // this.$refs.dialogRef.formData = data.mes
        },
    }
}
</script>

<style scoped>
.check label:after {
    content: ' *';
    color: #999;
    font-size: 150%;
}

.title {
    border-left: 3px solid #3590eb;
    padding-left: 8px;
    font-weight: bold;
    font-size: 16px;
    color: #333333;
}

.tipstyle {
    background-color: #cad5ff;
    border-color: #8ca3ff;
}

.config-content {
    height: 280px;
    overflow: hidden;
}

.config-content:hover {
    overflow-y: auto;
    overflow-x: hidden;
}

.config-foot-btn {
    position: absolute;
    bottom: 10px;
    right: 10px;
}

.config-list {
    height: 280px;
    overflow-y: hidden;
}

.config-list:hover {
    overflow-y: auto;
}

.list-item {
    padding: 8px 10px;
    margin-bottom: 10px;
    background-color: rgb(247, 247, 247);
}

.list-item:hover {
    background-color: rgb(233, 233, 233);
}
</style>